import { Init, Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { GoodsInfoEntity } from '../entity/info';
import { GoodsSpecService } from './spec';
import { GoodsPriceCalculatorService } from './priceCalculator';


/**
 * 商品信息
 */
@Provide()
export class GoodsInfoService extends BaseService {
  @InjectEntityModel(GoodsInfoEntity)
  goodsInfoEntity: Repository<GoodsInfoEntity>;

  @Inject()
  goodsSpecService: GoodsSpecService;

  @Inject()
  priceCalculatorService: GoodsPriceCalculatorService;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.goodsInfoEntity);
  }

  /**
   * 修改之后
   * @param data
   * @param type
   */
  async modifyAfter(data: any, type: 'add' | 'update' | 'delete') {
    if ((type == 'add' || type == 'update') && data.specs) {
      // 保存规格
      await this.goodsSpecService.save(data.id, data.specs);
    }
    if (type == 'delete') {
      // 删除规格
      await this.goodsSpecService.removeByGoodsId([data.id]);
    }
  }

  async page(query: any, option: any, connectionName?: any): Promise<{ list: any; pagination: { page: number; size: number; total: number; }; }> {
    const res = await super.page(query, option, connectionName)
    const userId = this.getUserId('app') || query.userId
    if (userId) {
      res.list.forEach(async (info)=>{
        const price = await this.priceCalculatorService.calculatePrice(userId, info.id)
        if (price > 0) {
          info.price = price.toFixed(2)
        }
      })
    }
    return res
  }

  /**
   * 详情
   * @param id
   * @param infoIgnoreProperty
   * @returns
   */
  async info(id: any, infoIgnoreProperty?: string[]) {
    if (!id) return;
    

    const info = await super.info(id, infoIgnoreProperty);
    if (info) {
      // 获取规格
      info.specs = await this.goodsSpecService.getByGoodsId(info.id);
    }
    const userId = this.getUserId('app')
    if (userId) {
      // 计算特定价格
      const price = await this.priceCalculatorService.calculatePrice(userId, id)
      if (price) {
        info.price = price.toFixed(2)
      }
    }
    return info;
  }
}
